package com.qbw.app.module.home.holder;

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.SPUtils;
import com.lib.util.StringUtil;
import com.lib.util.ToastUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.HomeHolderActionBinding;
import com.qbw.app.model.FindData;
import com.qbw.app.model.Location;
import com.qbw.app.model.Vehicle;
import com.qbw.app.model.VehicleHomeInfo;
import com.qbw.app.module.common.holder.CommonHolder;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.home.fragment.HomeFragment;
import com.qbw.app.module.mine.activity.FirmwareUpgradeActivity;
import com.qbw.app.module.vehicle.activity.VehicleFindSettingActivity;
import com.qbw.app.request.impl.VehicleRequest;
import com.qbw.core.observable.ObservableInt;
import com.tbox.tbsdk.HexUtil;
import com.tbox.tbsdk.TBoxSDK;

import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.qbw.app.request.impl.VehicleRequest.METHOD_SEARCH_VEHICLE;

/**
 * @author xiansx
 * @date 2020-10-12
 */
public class HomeActionHolder extends CommonHolder<HomeActionHolder.Data, HomeHolderActionBinding> implements View.OnClickListener, View.OnAttachStateChangeListener,
        TBoxSDK.DeviceConnectingListener
{

    private LoadingPopupView loadingPopup;
    private boolean isBtConnectStatus;
    private boolean isBtPowerStatus = true ;
    private CountDownTimer countDownTimer;
    public static BtConnectStatusListener mBtConnectStatusListener;

    public static BtConnectStatusListener getmBtConnectStatusListener() {
        return mBtConnectStatusListener;
    }

    public static void setmBtConnectStatusListener(BtConnectStatusListener mBtConnectStatusListener) {
        HomeActionHolder.mBtConnectStatusListener = mBtConnectStatusListener;
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                downtime--;
                if (downtime > 0) {
                    mBinding.ivSearchVehicle.setImageResource(R.drawable.nm_icon_light_normal_not);
                    mBinding.tvDownTime.setText(downtime + "后再次点击");
                    mHandler.sendEmptyMessageDelayed(0, 1000);
//                    itemView.setOnClickListener(false ? mClickListenerItem : null);
                    isSearchVehicle = false;
                } else {
                    mBinding.ivSearchVehicle.setImageResource(R.drawable.nm_icon_light_normal);
                    mBinding.tvDownTime.setText(20 + "后再次点击");
                    mBinding.tvDownTime.setVisibility(View.GONE);
//                    itemView.setOnClickListener(true ? mClickListenerItem : null);
                    isSearchVehicle = true;
                }
                return true;
            }
            return false;
        }
    });
    private ObservableInt mCountTime = new ObservableInt();
    private FindData mFindData;
    private int downtime = 20;
    private boolean isSearchVehicle = false;

    public HomeActionHolder(Context context, ViewGroup viewParent) {
        super(context, R.layout.home_holder_action, viewParent);
        itemView.addOnAttachStateChangeListener(this);
    }



    @Override
    public void bindData(int position, Data data) {
        super.bindData(position, data);
        setmBtConnectStatusListener(new BtConnectStatusListener() {
            @Override
            public void connectstatus(boolean status) {
                isBtConnectStatus = status;
                if(status){
                    mBinding.ivBtLockStatus.setBackgroundResource(R.drawable.bt_lock_open);
                    mBinding.tvBtStatus.setText(R.string.vehicle_bt_connect);
                    mBinding.tvBtStatus.setTextColor(mContext.getResources().getColor(R.color.nm_exception));
                    int isACC = SPUtils.getInstance().getInt(Constant.KEY_ACC_STATUS);
                    if(isACC == 1){
                        isBtPowerStatus = false;
                    }else{
                        isBtPowerStatus =true;
                    }
                }else{
                    mBinding.ivBtLockStatus.setBackgroundResource(R.drawable.bt_lock_close);
                    mBinding.imageStatus.setBackgroundResource(R.drawable.xr_icon_switch_off);
                    mBinding.tvBtStatus.setText(R.string.vehicle_bt_not_connect);
                    mBinding.tvBtStatus.setTextColor(mContext.getResources().getColor(R.color.color_999999));
                    dissDialog();
                }
                Log.e("isStatus", status + "");
            }
        });

        getLightDataNm();
        mBinding.setCount(mCountTime);
        updateItemEnabled();
        mBinding.executePendingBindings();
        mBinding.setLocation(data.getHomeInfo().getLocation());
        mBinding.imageStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( SPUtils.getInstance().getBoolean(Constant.KEY_BT_STATUS)){
                    loadingDialog();
                    setBtPowerStatus(isBtPowerStatus);
                }
            }
        });

    }

//    private void startDownTimer(){
//        countDownTimer = new CountDownTimer(20000,1000) {
//            @Override
//            public void onTick(long millisUntilFinished) {
//                Log.e("lanbin",(millisUntilFinished / 1000) + "s");
//            }
//
//            @Override
//            public void onFinish() {
//
//                dissDialog();
//            }
//        };
//    }
//
//    private void cancelDownTimer(){
//        if(countDownTimer !=null ){
//            countDownTimer.cancel();
//        }
//    }

    private void setBtPowerStatus(boolean isLock) {
        if (isLock) {
            TBoxSDK.getInstance(null).powerOn(new TBoxSDK.DeviceControlListener() {
                @Override
                public void onControlSuccess() {
                    isBtPowerStatus = false;
                    mBinding.imageStatus.setBackgroundResource(R.drawable.xr_icon_switch_on);
                    dissDialog();
                    ToastUtil.showToast(mContext, "上电成功");
                }

                @Override
                public void onControlFailed(int code) {
                    dissDialog();
                    ToastUtil.showToast(mContext, "上电失败" );
                }
            });
        } else {
            TBoxSDK.getInstance(null).powerOff(new TBoxSDK.DeviceControlListener() {
                @Override
                public void onControlSuccess() {
                    isBtPowerStatus = true;
                    mBinding.imageStatus.setBackgroundResource(R.drawable.xr_icon_switch_off);
                    dissDialog();
                    ToastUtil.showToast(mContext, "下电成功");
                }

                @Override
                public void onControlFailed(int code) {
                    dissDialog();
                    ToastUtil.showToast(mContext, "下电失败 ");
                }
            });
        }

    }

    /**
     * 查看寻车数据状态
     */
    private void getLightDataNm() {
        if (!TextUtils.isEmpty(mData.getHomeInfo().getVehicle().getVehicleCode())) {
            mGeneralManager.getRequestManager()
                    .getVehicleRequest()
                    .getLightDataNm(mData.getHomeInfo().getVehicle().getVehicleCode(),
                            this)
                    .execute();
        }
    }

    private void updateItemEnabled() {
        boolean enable = false;
        if (mFindData != null) {
            int lightSwitch = mFindData.getLightSwitch();
            int duration = mFindData.getLightDuration();
            Vehicle vehicle = mData.getHomeInfo().getVehicle();
            if (lightSwitch != 1) {
                enable = false;
                mBinding.tvCount.setText(R.string.search_vehicle_off);
            } else {
                if (vehicle.getDrivingState() == Constant.VEHICLE_STATUS_DRIVING) {
                    enable = false;
                    mBinding.tvCount.setText(R.string.search_vehicle_on);
                    mBinding.ivSearchVehicle.setImageResource(R.drawable.nm_icon_light_normal_not);
                } else {
                    long flameoutLastTime = mData.getHomeInfo().getFlameoutLastTime();
                    long durationTime = duration * 60 * 60 * 1000l;
                    long nowTime = new Date().getTime();
                    long stepCount = nowTime - flameoutLastTime;
                    if (stepCount > 0 && stepCount < durationTime) {
                        enable = true;
                        formatTimeDuration(mBinding.tvCount, durationTime - stepCount);
                    } else {
                        enable = false;
                        mBinding.tvCount.setText(R.string.search_vehicle_timeout);
                        mBinding.ivSearchVehicle.setImageResource(R.drawable.nm_icon_light_normal_not);

                    }
                }
            }
        }
//        mBinding.ivSearchVehicle.setImageResource(enable ? R.drawable.nm_icon_light_normal : R.drawable.nm_icon_light_normal_not);
        itemView.setOnClickListener(false ? mClickListenerItem : null);
        isSearchVehicle = enable;
        mBinding.ivFindSetting.setOnClickListener(this);
        mBinding.clSearchVehicle.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_find_setting) {
            VehicleFindSettingActivity.startActivity(mContext, mData.getHomeInfo().getVehicle());
        } else if (v.getId() == R.id.cl_search_vehicle) {
            if (isSearchVehicle) {
                showLoading("");
                downtime = mData.getHomeInfo().getVehicle().getWaitTime();
                mBinding.tvDownTime.setText(downtime + "后再次点击");
                mBinding.tvDownTime.setVisibility(View.VISIBLE);
                mGeneralManager.getRequestManager()
                        .getVehicleRequest()
                        .searchVehicle(mData.getHomeInfo().getVehicle().getVehicleCode(), this)
                        .execute();
            }

        }
    }

    @Override
    protected void onClickItem() {
        super.onClickItem();

//        startCountTime();
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_SEARCH_VEHICLE)) {
            UniversalToastUtil.showToast(ResUtil.getString(R.string.search_vehicle_success));
            mHandler.removeCallbacks(mRunnCountTime);
            mHandler.post(mRunnCountTime);

            closeLoading();
        } else if (method.equals(VehicleRequest.METHOD_LIGHT_DATA_V)) {
            FindData.Response response = (FindData.Response) entity;
            mFindData = response.getData();
        }

//        mCountTime.setValue(20);
        updateItemEnabled();
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_SEARCH_VEHICLE)) {
            UniversalToastUtil.showToast(ResUtil.getString(R.string.search_vehicle_failed));
            mHandler.removeCallbacks(mRunnCountTime);
            mHandler.post(mRunnCountTime);

            closeLoading();
        }
//        mCountTime.setValue(20);
        updateItemEnabled();
    }

    @Override
    public void onViewAttachedToWindow(View v) {

    }

    @Override
    public void onViewDetachedFromWindow(View v) {
        mHandler.removeCallbacks(mRunnCountTime);
    }


    private Runnable mRunnCountTime = new Runnable() {
        @Override
        public void run() {
            Log.e("111111", mCountTime.getValue() + "");
            mHandler.obtainMessage();
            mHandler.sendEmptyMessage(0);
        }
    };

    @Override
    public void onDeviceConnected() {

    }

    @Override
    public void onDeviceConnectFailed(int errorCode) {

    }

    @Override
    public void onDeviceDisconnected(int errorCode) {

    }

    @Override
    public void onRssiUpdated(int rssi) {

    }

    @Override
    public void onDeviceStatusSync(TBoxSDK.LockStatus lockStatus, TBoxSDK.DefendStatus defendStatus, TBoxSDK.ACCStatus accStatus) {

    }


    public static class Data {
        private VehicleHomeInfo homeInfo;

        public Data(VehicleHomeInfo homeInfo) {
            this.homeInfo = homeInfo;
        }

        public VehicleHomeInfo getHomeInfo() {
            return homeInfo;
        }

        public void setHomeInfo(VehicleHomeInfo homeInfo) {
            this.homeInfo = homeInfo;
        }


    }

    /**
     * 格式化时间
     *
     * @param textView
     * @param duration
     */
    private void formatTimeDuration(TextView textView, double duration) {
        duration = duration / 1000l;
        int hour = (int) duration / (60 * 60);
        double left = duration % (60 * 60);
        int min = (int) left / 60;
        left = left % 60;
        int second = (int) left;
        StringBuffer sb = new StringBuffer();
        StringBuffer sbZh = new StringBuffer();

        if (hour > 0) {
            sb.append(hour).append("h");
            sbZh.append(hour).append("小时");
        }
        if (min > 0) {
            sb.append(min).append("m");
            sbZh.append(min).append("分");
        }
        if (second > 0) {
            //sb.append(second).append("s");
        }
        if ("zh".equals(Locale.getDefault().getLanguage())) {
            textView.setText(String.format(mContext.getString(R.string.search_vehicle_counttime), sbZh.toString()));
        } else {
            textView.setText(String.format(mContext.getString(R.string.search_vehicle_counttime), sb.toString()));

        }
    }



    public interface BtConnectStatusListener {
        public void connectstatus(boolean status);
    }


    private void loadingDialog() {
        loadingPopup = (LoadingPopupView) new XPopup.Builder(mContext)
                .dismissOnTouchOutside(false)
                .asLoading("正在下发指令")
                .show();
    }

    private void dissDialog() {
        if(loadingPopup != null){
            loadingPopup.delayDismissWith(1000, new Runnable() {
                @Override
                public void run() {
//                ToastUtils.showShort("联系师父不成功");
                }
            });
        }
    }

}
